<template>
  <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
    <el-menu>
      <el-menu-item index="welcome">
        <template #title>
          <router-link to="/hello">
            <i class="el-icon-location"></i>
            <span>欢迎</span>
          </router-link>
        </template>
      </el-menu-item>
      <el-submenu v-for="c in level1" :index="c.id">
        <template #title><i class="el-icon-message"></i>{{ c.name }}</template>
        <el-menu-item-group>
          <el-menu-item v-for="s in c.children" :index="s.id" @click="handleQueryEbook(s.id)">
            {{s.name}}  
         </el-menu-item>
        </el-menu-item-group>
      </el-submenu>
    </el-menu>
  </el-aside>
</template>
<script>
import { defineComponent,getCurrentInstance,onMounted, ref, reactive, toRef } from "vue";
import Tool from "../util/tool";
import axios from "axios";
import { useStore } from "vuex";
export default {
  name: "the-aside",
  setup() {
    console.log("组件初始化");
    const { ctx } = getCurrentInstance()
    const level1 = ref();
    let categorys;
    /**
     * 分类数据查询
     **/
    const handleQueryCategory = () => {
      console.log("分类数据查询");
      let _this = this;
      axios
        .get("/category/all")
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            categorys = data.content;
            console.log("原始数组：", categorys);

            level1.value = [];
            level1.value = Tool.array2Tree(categorys, 0);
            console.log("树型结构：", level1.value);
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    
    /**
     * 根据电子书二级分类查询电子书
     */
    const store=useStore();
    const ebooks=ref();
    function handleQueryEbook(sid){
      console.log("二级分类id=>",sid)
      console.log(ctx.$root.$router)
      axios.get('/ebook/list',{
        params:{page:1,size:100,category2Id:sid}
      }).
      then(function(response){
        const data=response.data
        ebooks.value=data.content.list;
        console.log("二级分类电子书：",ebooks.value)
        console.log("store=>",store)
        store.commit('setEbooks',ebooks.value)
        ctx.$root.$router.push({name:'home'})
      }).catch(function (error) {
        console.log(error);
      });
    }

    onMounted: {
      console.log("onMounted=>");
      handleQueryCategory();
    }

    return {
      level1,
      handleQueryEbook
    };
  },
};
</script>
<style>
.el-aside {
  color: #333;
}
</style>